import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:recipe/detail.dart';
import 'package:recipe/global.dart';
import 'package:recipe/http-manager.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List recipeDateList = [];
  ScrollController _listController = ScrollController();
  bool listLoading = false;
  String searchName = '';
  int page = 2;
  @override
  void initState() {
    EasyLoading.instance.loadingStyle = EasyLoadingStyle.light;
    EasyLoading.instance.maskType = EasyLoadingMaskType.black;
    print("走你了");
    _listController.addListener(() {
      if (_listController.position.pixels >=
          _listController.position.maxScrollExtent) {
        if (page > 200) {
          EasyLoading.showToast('没有更多了');
          return;
        }
        if (!listLoading) {
          setState(() => {listLoading = true});
          EasyLoading.show(status: '正在加载');
          recipeList(page, 0, 'hot').then((res) {
            setState(() {
              recipeDateList.addAll(res);
              listLoading = false;
              EasyLoading.dismiss();
              page++;
            });
          });
        }
      }
    });

    recipeList(1, 0, 'hot').then((res) {
      setState(() {
        recipeDateList = res;
        listLoading = false;
      });
    });
    super.initState();
  }

  recipeList(int page, int type, String order) async {
    String url = "home_list?" +
        "page=" +
        page.toString() +
        "&type=" +
        type.toString() +
        "&order=" +
        order;

    if (searchName != '') {
      url = "search?" + "page=" + page.toString() + "&name=" + searchName;
    }

    print("url......${url}");
    try {
      var response = await HttpUtils.request(url, method: HttpUtils.GET);

      return response['data'];
    } catch (e) {
      print(e);
    }
  }

  List<Widget> renderRecipeList(recipeDateList) {
    List<Widget> list = [];
    List.generate(recipeDateList.length, (index) {
      String str = json.encode(recipeDateList[index]);
      final item = json.decode(str);
      list.add(
        InkWell(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => DetailPage(id: item['id'].toString()),
                ),
              );
            },
            child: Container(
              decoration: BoxDecoration(color: Global.cardBackgroundColor),
              padding: EdgeInsets.all(8),
              width: MediaQuery.of(context).size.width / 2,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Container(
                      child: ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                    child: FadeInImage.assetNetwork(
                      placeholder: 'assets/images/placeholder.png',
                      fadeInDuration: const Duration(milliseconds: 500),
                      image: item['fcover'],
                    ),
                  )),
                  SizedBox(height: 5),
                  Text(
                    item['title'],
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 11,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  SizedBox(height: 5),
                  Text(
                    item['message'],
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: Global.fontSecondColor,
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
            )),
      );
    });
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return recipeDateList.length == 0
        ? Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 20),
              Text(
                "正在加载",
                style: TextStyle(color: Global.fontSecondColor),
              )
            ],
          )
        : Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.yellow[700],
              titleSpacing: 15,
              automaticallyImplyLeading: false, //隐藏返回箭头
              title: Container(
                decoration: new BoxDecoration(
                  border: Border.all(color: Colors.white, width: 1.0), //灰色的一层边框
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(5.0)),
                ),
                alignment: Alignment.center,
                height: 38,
                padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
                child: TextField(
                  onChanged: (text) {
                    //内容改变的回调
                    print('change $text');
                    setState(() {
                      searchName = text;
                    });
                  },
                  decoration: InputDecoration(
                      contentPadding: EdgeInsets.all(10.0),
                      // focusedBorder: OutlineInputBorder(
                      //   borderSide: BorderSide(color: Colors.white, width: 1.0),
                      // ),
                      border: InputBorder.none,
                      hintText: '搜搜自己想吃的美食吧~'),
                ),
              ),
              actions: [
                new IconButton(
                    icon: new Icon(Icons.search),
                    tooltip: '搜索',
                    onPressed: () {
                      recipeList(1, 0, 'hot').then((res) {
                        setState(() {
                          recipeDateList = res;
                        });
                      });
                    }),
              ],
            ),
            // appBar: SearchBarDemoPage,
            body: Container(
              child: SingleChildScrollView(
                controller: _listController,
                // child: SearchBarDemoPage(),
                child: Wrap(
                  children: renderRecipeList(recipeDateList),
                ),
              ),
            ),
          );
  }
}
